package com.qianfeng.smartmetting.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qianfeng.smartmetting.entity.User;
import com.qianfeng.smartmetting.entity.dto.LoginDTO;
import com.qianfeng.smartmetting.service.UserDao;
import com.qianfeng.smartmetting.util.CommonResult;
import com.qianfeng.smartmetting.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserDao userDao;
    //用户列表
    @GetMapping("/list")
    public Map list(int page, int limit){
        try{
            //List<User> list = userDao.list();
            //mybatisplus 分页
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            Page<User> page1 = new Page<>(page,limit);
            IPage<User> obj = userDao.page(page1,queryWrapper);
            return CommonResult.ok("查询成功",obj);
        }catch (Exception e){
            return CommonResult.error(-1,"发生异常");
        }
    }

    @PostMapping("/add")
    public Map add(@RequestBody User user){
        Integer flag = userDao.saveUserDetails(user);
        String msg = "";
        if(flag == 1){
            msg = "添加成功";
        }else if(flag == 2){
            msg = "用户名已存在";
        }else{
            msg = "添加失败";
        }
        return CommonResult.ok(msg,null);
    }

    //添加用户
//    @PostMapping("/add")
//    public Map add(User user){
//        try{
//            //添加功能，判断用户名是否唯一
//            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("user_name",user.getUserName());
//            User obj = userDao.getOne(queryWrapper);
//            //进行判断，不为null 则证明该用户名存在
//            if (obj!=null){
//                return CommonResult.error(2,"该用户已存在");
//            }
//            boolean flag = userDao.save(user);
//            System.out.println(user);
//            return CommonResult.ok(flag?"添加成功":"添加失败",null);
//        }catch (Exception e){
//            return CommonResult.error(-1,"发生异常");
//        }
//    }

    //修改用户
    //RESTFUL风格 不需要？参数接收，用斜杠进行分割
    @PostMapping("/modify/{id}")
    public Map Modify(@PathVariable(name = "id") Integer  id, User user){
        try{
            user.setUserId(id);
            boolean flag = userDao.updateById(user);
            return CommonResult.ok(flag?"修改成功":"修改失败",null);
        }catch (Exception e){
            return CommonResult.error(-1,"发生异常");
        }
    }

    //删除单个用户
    @DeleteMapping("/delete/{id}")
    public Map delete(@PathVariable(name = "id") Integer id){
        try{
            boolean flag = userDao.removeById(id);
            return CommonResult.ok(flag?"删除成功":"删除失败",null);
        }catch (Exception e){
            return CommonResult.error(-1,"发生异常");
        }
    }

    //删除多个用户 @RequestBody 接收非表单类数据
    @DeleteMapping("/delete")
    public Map delete(@RequestBody String[] ids){
        try{
            boolean flag = userDao.removeByIds(Arrays.asList(ids));
            return CommonResult.ok(flag?"删除成功":"删除失败",null);
        }catch (Exception e){
            return CommonResult.error(-1,"发生异常");
        }
    }

    //通过id查询单个用户信息
    @GetMapping("/{id}")
    public Map info(@PathVariable(name = "id") Integer id) {
        try {
            User info = userDao.getById(id);
            return CommonResult.ok(info!=null?"查询成功":"当前用户不存在", info);
        } catch (Exception e) {
            return CommonResult.error(-1,"发生异常");
        }
    }

    //用户名（手机号）和密码进行登录,前后端分离，接收json数据
    @PostMapping("/login")
    public Map login(@RequestBody LoginDTO userDetail){
        try{
            //首先 判断用户是否存在
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_name",userDetail.getUsername());
            User user = userDao.getOne(queryWrapper);
            if(user==null){
                return CommonResult.error(0,"用户不存在");
            }else{
                //将存在数据库中的密码取出
                String password = user.getUserPassword();
                BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
                boolean matches = encoder.matches(userDetail.getPassword(), password.substring(8));
                if (matches){
                    JwtUtil jwtUtil = new JwtUtil();
                    String token = jwtUtil.generateToken(userDetail.getUsername());
                    Map map = new HashMap();
                    map.put("data",user);
                    map.put("token",token);
                    return CommonResult.ok("登录成功",map);
                }
                return CommonResult.error(2,"用户名或密码错误");
            }
            //对传入的密码进行加密
//            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(4);
//            String encode = bCryptPasswordEncoder.encode(userDetail.getPassword());
//            //mybaitsplus 需要进行条件查询是使用QueryWrapper
//            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("user_name",userDetail.getUsername());
//            queryWrapper.eq("user_password","{bcrypt}"+encode);
//            User user = userDao.getOne(queryWrapper);
//            return CommonResult.ok(user!=null?"登录成功":"用户名或密码错误",user);
        }catch (Exception e){
            return CommonResult.error(-1,"发生异常");
        }
    }
}
